package com.zqwh.yj.sdk.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;

/**
 * Created by eason.yang on 2018/5/31.
 */
public class SerialPortUtils {
    public boolean serialPortStatus = false; //是否打开串口标志
    public String data_;
    public boolean threadStatus; //线程状态，为了安全终止线程

    public String uartName;
    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;
    public int baudRate;

    /**
     * 打开串口
     * @return serialPort串口对象
     */
    public SerialPort openSerialPort(String name, String path, int baudrate){
        try {
            uartName = name;
            baudRate = baudrate;
            serialPort = new SerialPort(new File(path),baudrate,0);
            this.serialPortStatus = true;
            threadStatus = false; //线程状态

            //获取打开的串口中的输入输出流，以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();

            new ReadThread().start(); //开始线程监控是否有数据要接收
        } catch (IOException e) {
            LogUtils.error("Fail to connect uart ("+uartName+")"+", path is "+path+", baudrate rate is "+baudrate);
            return null;
        }
        LogUtils.logout("Success to connect uart ("+uartName+")"+", path is "+path+", baudrate rate is "+baudrate);
        return serialPort;
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort(){
        try {
            inputStream.close();
            outputStream.close();

            this.serialPortStatus = false;
            this.threadStatus = true; //线程状态
            serialPort.close();
        } catch (IOException e) {
            LogUtils.error("关闭串口（"+uartName+"）异常"+e.toString());
            return;
        }
        LogUtils.logout("关闭串口（"+uartName+"）成功");
    }

    /**
     * 发送串口指令（字节）
     * @param data String数据指令
     */
    public void sendSerialPort(byte[] data){
        try {
            if (data.length > 0) {
                outputStream.write(data);
//                outputStream.write('\n');
                outputStream.flush();
            }
        } catch (IOException e) {
            LogUtils.error("发送串口("+uartName+")数据失败"+e.toString());
        }
    }

    /**
     * 发送串口指令（字符串）
     * @param data String数据指令
     */
    public void sendSerialPort(String data){
        try {
            byte[] sendData = data.getBytes(); //string转byte[]
            this.data_ = new String(sendData); //byte[]转string
            if (sendData.length > 0) {
                outputStream.write(sendData);
                outputStream.write('\n');
//                outputStream.write('\r'+'\n');
                outputStream.flush();
            }
        } catch (IOException e) {
            LogUtils.error("发送串口("+uartName+")数据失败"+e.toString());
        }
    }

    /**
     * 单开一线程，来读数据
     */
    private class ReadThread extends Thread{
        @Override
        public void run() {
            super.run();
            //判断进程是否在运行，更安全的结束进程
            while (!threadStatus){
                //64   1024
                byte[] buffer = new byte[1024];
                int size; //读取数据的大小
                try {
                    size = inputStream.read(buffer);
                    if (size > 0){
                        String data = ByteUtils.byteArrayToHexString(buffer);
                    }
                    if (size > 0 && onDataReceiveListener != null){
                        onDataReceiveListener.onDataReceive(buffer, size);
                    }
                } catch (IOException e) {
                    LogUtils.error("串口("+uartName+")数据读取异常"+e.toString());
                }
            }

        }
    }

    //这是写了一监听器来监听接收数据
    public OnDataReceiveListener onDataReceiveListener = null;
    public interface OnDataReceiveListener {
        void onDataReceive(byte[] buffer, int size);
    }
    public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        onDataReceiveListener = dataReceiveListener;
    }

    public int getBaudRate() {
        return baudRate;
    }

    public void setBaudRate(int baudRate) {
        this.baudRate = baudRate;
    }
}
